import { Tag } from "antd"

//处理url参数对象
export const stringify = (search) => {
    if (search === null || search === undefined) {
        return ''
    }
    return Object.entries(search).reduce((a, b, i) => {
        if ((b[1] ?? '') !== '') {
            if (Array.isArray(b[1])) {
                for (var j = 0; j < b[1].length; j++) {
                    if (b[1][j] !== '') {
                        a += `${a === '' ? '' : '&'}${b[0]}=${b[1][j]}`
                    }
                }
            } else {
                a += `${a === '' ? '' : '&'}${b[0]}=${b[1]}`
            }
        }
        return a
    }, '')
}

export const getCookie = async (name) => {
    // await user.updateCsrf();
    if (!document.cookie) {
        return null;
    }
    const csrfCookies = document.cookie.split(';')
        .map(c => c.trim())
        .filter(c => c.startsWith(name + '='));
    if (csrfCookies.length === 0) {
        return null;
    }
    return decodeURIComponent(csrfCookies[0].split('=')[1]);
}

//文件路径截取文件名称
export const captureFile = (file_url, name) => {
    if (!file_url) {
        return
    }
    let file = file_url.split('/')[file_url.split('/').length - 1];
    const regex = /-([^-]{8})/g;
    const matches = file.match(regex);
    if (matches) {
        const lastMatch = matches[matches.length - 1];
        const formatFile = file.replace(lastMatch, '');
        if (name && formatFile !== name) {
            return name + '.' + formatFile.split('.')[formatFile.split('.').length - 1]
        } else {
            return formatFile
        }
    }
    return file
}

export const downloadFile = (data, name, accept) => {
    let blob = new Blob([data]);
    let url = window.URL.createObjectURL(blob);
    const link = document.createElement("a"); // 创建a标签
    link.href = url;
    link.download = name + (accept || ".xlsx")
    link.click();
    URL.revokeObjectURL(url); // 释放内存
}

export const downloadTool = (data, name) => {
    let blob = new Blob([data], { type: "application/zip;charset-UTF-8" });
    let url = window.URL.createObjectURL(blob);
    const link = document.createElement("a"); // 创建a标签
    link.href = url;
    link.download = name + ".zip";
    link.click();
    URL.revokeObjectURL(url); // 释放内存
}

// 获取路径后的文件名
export const getFileName = (fullFileName) => {
    return fullFileName.substring(fullFileName.lastIndexOf('/') + 1, fullFileName.length);
}

export const computerOptions = [
    {
        label: 'Window操作机',
        value: 1,
    }, {
        label: 'Liunx操作机',
        value: 2,
    }, {
        label: 'Unix',
        value: 3,
    }, {
        label: '开放麒麟',
        value: 4,
    }, {
        label: '优麒麟',
        value: 5,
    }, {
        label: '深度',
        value: 6,
    }, {
        label: '统信',
        value: 7,
    }, {
        label: 'Openeuler',
        value: 8,
    }, {
        label: 'Startos',
        value: 9,
    },
];

export const computerType = {
    1: 'Window操作机',
    2: 'Liunx操作机',
    3: 'Unix',
    4: '开放麒麟',
    5: '优麒麟',
    6: '深度',
    7: '统信',
    8: 'Openeuler',
    9: 'Startos'
}

export const optionLetter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

export const videoFile = (file_url) => {
    if (!file_url) {
        return
    }
    let file = file_url.split('/')[file_url.split('/').length - 1].split('.');
    return file.join('.')
}

// 文件大小
export function renderSize(value) {
    if (null == value || value === '' || value === 0) {
        return "0 Bytes";
    }
    const unitArr = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    let srcSize = parseFloat(value);
    let index = Math.floor(Math.log(srcSize) / Math.log(1024));
    let size = srcSize / Math.pow(1024, index);
    size = size.toFixed(2);
    return size + ' ' + unitArr[index];
}

// 定义过滤规则
export const filterRules = [
    { pattern: /&/g, replacement: '&amp;' }, // 替换 '&' 为 '&amp;'
    // { pattern: /</g, replacement: '&lt;' }, // 替换 '<' 为 '&lt;'
    // { pattern: />/g, replacement: '&gt;' }, // 替换 '>' 为 '&gt;'
    // { pattern: /"/g, replacement: '&quot;' }, // 替换 '"' 为 '&quot;'
    // { pattern: /'/g, replacement: '&apos;' }, // 替换 ''' 为 '&quot;'
    // { pattern: /©/g, replacement: '&copy;' }, // 替换 '"' 为 '&quot;'
    // { pattern: /®/g, replacement: '&reg;' }, // 替换 '"' 为 '&quot;'
    // { pattern: /™/g, replacement: '&trade;' }, // 替换 '"' 为 '&quot;'
];

export const issueTag = {
    '-1': { name: '已回收', color: 'red' },
    0: { name: '待下发', color: 'volcano' },
    1: { name: '已下发', color: 'green' }
};

export const statusTag = {
    0: { name: '进行中', color: 'green' },
    1: { name: '未开始', color: 'orange' },
    2: { name: '已结束', color: 'red' },
    3: { name: '已暂停', color: 'orange' }
};

export const onlineTag = {
    '-1': { name: '下线', color: 'red' },
    1: { name: '上线', color: 'green' }
};

export const paperType = {
    0: '理论题目',
    1: '实操题目',
    3: '漏洞题目',
    4: '场景题目',
    // 5: 'CTF对抗题目',
}

export const testPaperType = {
    1: '理论',
    2: '实操',
    3: '理论 + 实操'
};

export const paperOptions = [
    {
        label: '理论题目',
        value: 0,
    },
    {
        label: '实操题目',
        value: 1,
    },
    // {
    //     label: '漏洞题目',
    //     value: 3,
    // },
    {
        label: '场景题目',
        value: 4,
    },
    // {
    //     label: 'CTF对抗题目',
    //     value: 5,
    // },
]

export const vulnLevel = (text) => {
    switch (text) {
        case 1:
            return <Tag color="red" className='red-tag'>&nbsp;&nbsp;高危&nbsp;&nbsp;</Tag>
        case 2:
            return <Tag color="orange" className='yellow-tag'>&nbsp;&nbsp;中危&nbsp;&nbsp;</Tag>
        case 3:
            return <Tag color="cyan" className='green-tag'>&nbsp;&nbsp;低危&nbsp;&nbsp;</Tag>
        case 4:
            return <Tag color="blue" className='blue-tag'>&nbsp;&nbsp;信息&nbsp;&nbsp;</Tag>
        default:
            break;
    }
}

export const finishTag = {
    '-1': { name: '未提交', color: 'red' },
    0: { name: '已提交', color: 'processing' },
    1: { name: '已完成', color: 'green' }
};

export const rateFilters = [
    {
        text: '一星',
        value: 1
    }, {
        text: '二星',
        value: 2
    }, {
        text: '三星',
        value: 3
    }, {
        text: '四星',
        value: 4
    }, {
        text: '五星',
        value: 5
    }
]

export const competitionStatusTag = {
    1: { name: '进行中', color: 'green' },
    2: { name: '未开始', color: 'orange' },
    3: { name: '已结束', color: 'red' },
};

export const getTimes = (times) => {
    if (times && times > 0) {
        return <span>
            {formatTime(times).day !== '00' && formatTime(times).day + '天'}
            {formatTime(times).hour !== '00' && formatTime(times).hour + '小时'}
            {formatTime(times).minute !== '00' && formatTime(times).minute + '分钟'}
            {formatTime(times).second !== '00' && formatTime(times).second + '秒'}
        </span>
    } else {
        return '0秒'
    }
}

export const formatTime = (time) => {
    let day = 0;
    let hour = 0;
    let minute = 0;
    let second = 0;
    if (null !== time && "" !== time) {
        day = Math.floor(time / 86400);
        hour = Math.floor((time % 86400) / 3600);
        minute = Math.floor(((time % 86400) % 3600) / 60);
        second = Math.floor(((time % 86400) % 3600) % 60);
    }
    if (day < 10) {
        day = "0" + day
    }
    if (hour < 10) {
        hour = "0" + hour
    }
    if (minute < 10) {
        minute = "0" + minute
    }
    if (second < 10) {
        second = "0" + second
    }
    return {
        day: day.toString(),
        hour: hour.toString(),
        minute: minute.toString(),
        second: second.toString()
    };
}

export const formatDate = (date) => {
    var hour = Math.floor(date / 3600);
    var min = Math.floor(date / 60) % 60;
    var sec = date % 60;
    if (hour < 10) {
        hour = "0" + hour
    }
    if (min < 10) {
        min = "0" + min
    }
    if (sec < 10) {
        sec = "0" + sec
    }
    return hour + ":" + min + ":" + sec
}

export const taskLogType = {
    1: "开启",
    2: "提交",
    3: "启动",
    4: "延时",
    5: "释放",
    6: "领取",
    7: "完成",
    8: "重复训练",
    9: '重新测试',
    10: '解出'
}

export const learnTime = (count) => {
    let time = '';
    if (count < 60) {
        time = count + '秒'
    } else if (count < 3600) {
        time = Math.floor(count / 60) + '分钟'
    } else {
        time = Math.floor(count / 3600) + '小时'
    }
    return time
}

export const scriptTypeOptions = [
    {
        value: 1,
        label: 'bat'
    }, {
        value: 2,
        label: 'bash'
    }, {
        value: 3,
        label: 'python'
    },
]

export const toolType = {
    'scout': '侦察类',
    'attack': '进攻类',
    'defense': '防御类',
    'apply': '应用类',
}

export const accessFormOptions = [
    {
        value: 1,
        label: '本地',
    }, {
        value: 2,
        label: '远程',
    }
]

export const archOptions = [
    {
        value: 1,
        label: 'x86_64',
    },
    {
        value: 2,
        label: 'x86',
    },
]

export const osOptions = [
    {
        value: 1,
        label: 'Linux',
    }, {
        value: 2,
        label: 'Windows',
    }
]

export const shapeOptions = [
    {
        value: 1,
        label: '独立程序',
    }, {
        value: 2,
        label: '虚拟镜像',
    }, {
        value: 3,
        label: '实物设备',
    }
]

export const roleOptions = [
    {
        value: 1,
        label: '学员',
    }, {
        value: 2,
        label: '管理员',
    }, {
        value: 3,
        label: '超级管理员',
    }, {
        value: 4,
        label: '教员',
    }, {
        value: 5,
        label: '审计员',
    }
]

//文件类型
export const getFileType = (fileName) => {
    let suffix = ''; // 后缀获取
    let result = ''; // 获取类型结果
    if (fileName) {
        const flieArr = fileName.split('.'); // 根据.分割数组
        suffix = flieArr[flieArr.length - 1]; // 取最后一个
    }
    if (!suffix) return false; // fileName无后缀返回false
    suffix = suffix.toLocaleLowerCase(); // 将后缀所有字母改为小写方便操作
    // 匹配图片
    const imgList = ['png', 'jpg', 'jpeg', 'bmp', 'gif']; // 图片格式
    result = imgList.find(item => item === suffix);
    if (result) return 'image';
    // 匹配txt
    const txtList = ['txt'];
    result = txtList.find(item => item === suffix);
    if (result) return 'txt';
    // 匹配excel
    const excelList = ['xls', 'xlsx'];
    result = excelList.find(item => item === suffix);
    if (result) return 'excel';
    // 匹配word
    const wordList = ['doc', 'docx'];
    result = wordList.find(item => item === suffix);
    if (result) return 'word';
    // 匹配pdf
    const pdfList = ['pdf'];
    result = pdfList.find(item => item === suffix);
    if (result) return 'pdf';
    // 匹配ppt
    const pptList = ['ppt', 'pptx'];
    result = pptList.find(item => item === suffix);
    if (result) return 'ppt';
    // 匹配zip
    const zipList = ['rar', 'zip', '7z'];
    result = zipList.find(item => item === suffix);
    if (result) return 'zip';
    // 匹配视频
    // const videoList = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
    const videoList = ['mp4'];
    result = videoList.find(item => item === suffix);
    if (result) return 'video';
    // 匹配音频
    const radioList = ['mp3', 'wav', 'wmv'];
    result = radioList.find(item => item === suffix);
    if (result) return 'radio';
    // 其他文件类型
    return 'other';
}

export const pythonToolOptions = [
    {
        value: 1,
        label: 'python3.6',
    }, {
        value: 2,
        label: 'python3.8',
    }, {
        value: 3,
        label: 'python2.7',
    }
]

//大于1000转换成1位小数后面加k的字符
export const convertNumber = (num) => {
    if (num > 1000) {
        return (num / 1000).toFixed(1) + "k";
    }
    return num;
}

export const nodeTypeStatus = {
    1: { name: '待审核', color: 'orange' },
    2: { name: '通过', color: 'green' },
    3: { name: '不通过', color: 'red' },
}

const State = {
    // 等待
    PENDING: '0',
    // 执行中
    STARTED: '1',
    // 成功
    SUCCESS: '2',
    // 失败
    FAILURE: '3',
    // 取消任务
    REVOKE: '4',
    // 取消成功
    REVOKED: '5',
    IGNORED: 'n'
}
const checkList = [
    State.REVOKE,
    State.STARTED,
    State.PENDING,
    State.FAILURE,
    State.REVOKED,
    State.SUCCESS
]
export const aggStatus = (status) => {
    let obj = { key: 0, value: '' }
    for (const i in checkList) {
        const state = checkList[i]
        const index = status.indexOf(state)
        if (index > -1) {
            obj = { key: status.length - index, value: state }
            break
        }
    }
    return obj
}
export function filesize(size) {
    if (!size) return ''
    /* byte */
    const num = 1024.0

    if (size < num) return size + 'B'
    if (size < Math.pow(num, 2)) return (size / num).toFixed(2) + 'K' //kb
    if (size < Math.pow(num, 3)) return (size / Math.pow(num, 2)).toFixed(2) + 'M' //M
    if (size < Math.pow(num, 4)) return (size / Math.pow(num, 3)).toFixed(2) + 'G' //G
    return (size / Math.pow(num, 4)).toFixed(2) + 'T' //T
}

export const NumberToChinese = (num) => {
    if (num == 10) {
        return '十'
    } else if (num == 1) {
        return '一'
    }
    const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    const units = ['', '十', '百', '千', '万'];
    let result = '';
    let numStr = num.toString();
    for (let i = 0; i < numStr.length; i++) {
        let digit = parseInt(numStr.charAt(i));
        let unit = units[numStr.length - i - 1];
        if (digit === 0) {
            // 当前数字为0时不需要输出汉字，但需要考虑上一个数字是否为0，避免出现连续的零
            if (result.charAt(result.length - 1) !== '零') {
                result += '零';
            }
        } else {
            result += digits[digit] + unit;
        }
    }
    // 对于一些特殊的数字，如10、100等，需要在最前面加上“一”
    if (result.charAt(0) === '百') {
        result = '一' + result;
    } else if (result.charAt(0) === '千') {
        result = '一' + result;
    } else if (result.charAt(0) === '一' && num < 20) {
        result = result.substr(1, result.length);
    } else if (result.lastIndexOf('零') + 1 === result.length) {
        result = result.substr(0, result.length - 1);
    }
    return result;
}

export const base64ToFile = (base64String, fileName) => {
    const arr = base64String.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }

    return new File([u8arr], fileName, { type: mime });
}
export const splitPathname = ({ url, num }) => {
    // 根据 '/' 进行拆分，得到一个数组
    let segments = url.split('/');
    // 确保数组中有足够的元素来删除最后两个
    if (segments.length > num) {
        segments.splice(-num); // 从数组中移除最后两个元素
    } else if (segments.length === num) {
        // 如果只有两个段，则可能是一个根路径和一个段，或者只有根路径（'/'）
        // 这里我们假设如果只有两个段且第一个是空字符串（即原字符串以'/'开头），则保留根路径
        if (segments[0] === '') {
            segments = ['/']; // 只保留根路径
        } else {
            segments = []; // 或者返回一个空路径，根据实际需求决定
        }
    } else {
        // 如果只有一个段或没有段，直接返回一个空路径或原路径（根据实际需求）
        segments = []; // 这里我们返回一个空路径作为示例
    }
    // 用 '/' 重新拼接数组中的元素（如果需要的话）
    let resultPath = segments.join('/');
    // 如果结果路径是空字符串，则返回一个根路径（可选）
    if (resultPath === '') {
        resultPath = '/';
    }
    // 返回结果路径
    return resultPath;
}
export const taskObject = {
    1: '单兵任务',
    2: '分队任务',
    3: '编组联合'
}
export const timeToSeconds = (timeString) => {
    const parts = timeString.split(':').map(Number);
    return parts[0] * 3600 + parts[1] * 60 + parts[2];
}

export const dimensionList = ['目标环境', '攻击效果', '设备防护能力', '人员防护处置能力', '防御体系有效性']
export const srcUrl = (str) => {
    if (str) {
        const pa = []
        let externalUrl = false;
        // 匹配图片（g表示匹配所有结果i表示区分大小写）
        var imgReg = /<img.*?(?:>|\/>)/gi
        // 匹配src属性
        var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
        var arr = str.match(imgReg)
        // alert('所有已成功匹配图片的数组：' + arr)
        if (arr) {
            for (var i = 0; i < arr.length; i++) {
                var src = arr[i].match(srcReg)
                // 获取图片地址
                if (src[1] && (src[1].indexOf('https://') !== -1 || src[1].indexOf('http://') !== -1 || src[1].indexOf('file://') !== -1)) {
                    // alert('已匹配的图片地址' + (i + 1) + '：' + src[1])
                    pa.push(src[1])
                }
            }
        }
        if (pa.length > 0 && !str.includes(window.location.host)) {
            externalUrl = true
        } else {
            externalUrl = false
        }
        return externalUrl
    } else {
        return str
    }
}

export const openOfficeView = (fileUrl) => {
    let origin = window.location.origin;
    let pathname = window.location.pathname;
    let params = {
        filePath: `${origin}${fileUrl}`,
        mode: 'view'
    }
    hrefOnlyOffice(params)
    // window.open(`${origin}${pathname}#/office/viewer?${params}`)
}

// 数据采集策略规则列表展示内容
export const fieldValueContent = (nameList, record) => {
    let str = ''
    let rule = record?.field_rule_info || {}
    let value = record?.field_value_info || {}
    nameList.map((x, i) => {
        str += `[${value?.[x] ? `${value?.[x]}（${rule?.[x] === 'or' ? '非必需' : '必需'}）` : '--'}]${i + 1 === nameList.length ? '' : ' / '}`
    })
    return str
}

//antd 色块
export const antdColor = ['#d32029', '#d84a1b', '#d87a16', '#d89614', '#d8bd14', '#8bbb11', '#49aa19', '#13a8a8', '#1668dc', '#2b4acb', '#642ab5', '#cb2b83']
// 攻击手段
export const attackMethod = [
    {
        name: '攻击准备', value: '攻击准备',
        disableCheckbox: true,
        // disabled: true,
        children: [
            { name: '武器部署', value: '武器部署' },
            { name: '代理部署', value: '代理部署' },
            { name: '载荷生成', value: '载荷生成' },
            // { name: '操作系统扫描', value: '操作系统扫描' },
            // { name: '服务漏洞扫描', value: '服务漏洞扫描' },
            // { name: '数据库漏洞扫描', value: '数据库漏洞扫描' },
            // { name: '目录扫描', value: '目录扫描' },
            // { name: '指纹识别', value: '指纹识别' }
        ]
    },
    {
        name: '扫描探测手段', value: '扫描探测手段',
        disableCheckbox: true,
        // disabled: true,
        children: [
            { name: '网络地址扫描', value: '网络地址扫描' },
            { name: 'TCP端口扫描', value: 'TCP端口扫描' },
            { name: 'UDP端口扫描', value: 'UDP端口扫描' },
            { name: '操作系统扫描', value: '操作系统扫描' },
            { name: '服务漏洞扫描', value: '服务漏洞扫描' },
            { name: '数据库漏洞扫描', value: '数据库漏洞扫描' },
            { name: '目录扫描', value: '目录扫描' },
            { name: '指纹识别', value: '指纹识别' }
        ]
    },
    {
        name: '入侵渗透手段', value: '入侵渗透手段',
        disableCheckbox: true,
        children: [
            { name: '漏洞利用', value: '漏洞利用' },
            { name: '载荷攻击', value: '载荷攻击' },
            { name: '口令破解', value: '口令破解' },
            { name: '本地提权', value: '本地提权' },
            { name: '会话劫持', value: '会话劫持' },
            { name: '钓鱼攻击', value: '钓鱼攻击' },
            { name: '横向移动', value: '横向移动' },
        ]
    },
    {
        name: '远程控守手段', value: '远程控守手段',
        disableCheckbox: true,
        children: [
            { name: '应用程序攻击控守', value: '应用程序攻击控守' },
            { name: '数据库漏洞攻击控守', value: '数据库漏洞攻击控守' },
            { name: 'Shell获取攻击', value: 'Shell获取攻击' },
            { name: '内存马', value: '内存马' },
        ]
    },
    {
        name: '病毒攻击手段', value: '病毒攻击手段',
        disableCheckbox: true,
        children: [
            { name: '木马', value: '木马' },
            { name: '病毒', value: '病毒' },
            { name: '加壳', value: '加壳' },
            { name: '分离免杀', value: '分离免杀' },
            { name: '花指令', value: '花指令' },
        ]
    },
    {
        name: '服务破坏类手段', value: '服务破坏类手段',
        disableCheckbox: true,
        children: [
            { name: '数据链路层攻击', value: '数据链路层攻击' },
            { name: '网络层协议攻击', value: '网络层协议攻击' },
            { name: '传输层协议攻击', value: '传输层协议攻击' },
            { name: '应用层协议攻击', value: '应用层协议攻击' },
        ]
    }
];
export const enumData = [
    { text: '武器部署', value: '武器部署' },
    { text: '代理部署', value: '代理部署' },
    { text: '载荷生成', value: '载荷生成' },
    { text: '网络地址扫描', value: '网络地址扫描' },
    { text: 'TCP端口扫描', value: 'TCP端口扫描' },
    { text: 'UDP端口扫描', value: 'UDP端口扫描' },
    { text: '操作系统扫描', value: '操作系统扫描' },
    { text: '服务漏洞扫描', value: '服务漏洞扫描' },
    { text: '数据库漏洞扫描', value: '数据库漏洞扫描' },
    { text: '目录扫描', value: '目录扫描' },
    { text: '指纹识别', value: '指纹识别' },
    { text: '漏洞利用', value: '漏洞利用' },
    { text: '载荷攻击', value: '载荷攻击' },
    { text: '口令破解', value: '口令破解' },
    { text: '本地提权', value: '本地提权' },
    { text: '会话劫持', value: '会话劫持' },
    { text: '钓鱼攻击', value: '钓鱼攻击' },
    { text: '横向移动', value: '横向移动' },
    { text: '应用程序攻击控守', value: '应用程序攻击控守' },
    { text: '数据库漏洞攻击控守', value: '数据库漏洞攻击控守' },
    { text: 'Shell获取攻击', value: 'Shell获取攻击' },
    { text: '内存马', value: '内存马' },
    { text: '木马', value: '木马' },
    { text: '病毒', value: '病毒' },
    { text: '加壳', value: '加壳' },
    { text: '分离免杀', value: '分离免杀' },
    { text: '花指令', value: '花指令' },
    { text: '数据链路层攻击', value: '数据链路层攻击' },
    { text: '网络层协议攻击', value: '网络层协议攻击' },
    { text: '传输层协议攻击', value: '传输层协议攻击' },
    { text: '应用层协议攻击', value: '应用层协议攻击' },
]
// currentPage：当前页码
// size：当前每页数量
// originalCount：当前数据总数
// deletedCount：删除数量
export const calculateNewPage = (currentPage, size, originalCount, deletedCount) => {
    const newCount = Math.max(0, originalCount - deletedCount);
    const maxPage = Math.max(1, Math.ceil(newCount / size));
    return Math.min(currentPage, maxPage);
}

